package api

import (
	"net/http"
	"strconv"

	"alfred/models"
	"github.com/gin-gonic/gin"
)

// ExecuteFlow 手动启动Flow执行
func (h *Handler) ExecuteFlow(c *gin.Context) {
	id := c.Param("id")
	
	// 获取Flow信息
	flow, err := h.db.GetFlow(id)
	if err != nil {
		c.JSON(http.StatusNotFound, NewErrorResponse(404, "Flow not found"))
		return
	}

	// 从请求体获取执行参数
	var req struct {
		CommitID string `json:"commit_id"`
		Branch   string `json:"branch"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		// 如果没有提供参数，使用默认值
		req.Branch = flow.Branch
		req.CommitID = "HEAD"
	}

	// 异步执行Flow
	go func() {
		if err := h.executor.ExecuteFlow(flow.ID, req.CommitID, req.Branch); err != nil {
			// 错误已经在executor中处理了
		}
	}()

	c.JSON(http.StatusOK, NewSuccessResponse(gin.H{
		"message":   "Flow execution started",
		"flow_id":   flow.ID,
		"flow_name": flow.Name,
		"branch":    req.Branch,
		"commit_id": req.CommitID,
	}))
}

// GetFlowExecutionStatus 获取Flow执行状态
func (h *Handler) GetFlowExecutionStatus(c *gin.Context) {
	id := c.Param("id")
	execution, err := h.db.GetFlowExecution(id)
	if err != nil {
		c.JSON(http.StatusNotFound, NewErrorResponse(404, "Flow execution not found"))
		return
	}

	// 获取Node执行记录
	nodeExecutions, err := h.db.GetNodeExecutionsByFlowExecutionID(id)
	if err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}

	response := gin.H{
		"execution":       execution,
		"node_executions": nodeExecutions,
	}

	c.JSON(http.StatusOK, NewSuccessResponse(response))
}

// GetFlowExecutionHistory 获取Flow执行历史
func (h *Handler) GetFlowExecutionHistory(c *gin.Context) {
	flowID := c.Param("flow_id")
	
	// 分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	
	if page < 1 {
		page = 1
	}
	if limit < 1 || limit > 100 {
		limit = 20
	}

	executions, err := h.db.GetFlowExecutionsByFlowID(flowID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}

	// 简单分页
	start := (page - 1) * limit
	end := start + limit
	if start >= len(executions) {
		executions = []*models.FlowExecution{}
	} else {
		if end > len(executions) {
			end = len(executions)
		}
		executions = executions[start:end]
	}

	c.JSON(http.StatusOK, NewSuccessResponse(executions))
}

// GetAllFlowExecutions 获取所有Flow的执行记录
func (h *Handler) GetAllFlowExecutions(c *gin.Context) {
	// 分页参数
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	status := c.Query("status")
	
	if page < 1 {
		page = 1
	}
	if limit < 1 || limit > 100 {
		limit = 20
	}

	// 使用GORM查询，预加载Flow信息
	var executions []*models.FlowExecution
	query := h.db.Preload("Flow").Order("start_time DESC")
	
	if status != "" {
		query = query.Where("status = ?", status)
	}
	
	offset := (page - 1) * limit
	err := query.Limit(limit).Offset(offset).Find(&executions).Error
	if err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}

	// 转换为前端期望的格式
	type ExecutionResponse struct {
		ID         string  `json:"id"`
		FlowName   string  `json:"flow_name"`
		Status     string  `json:"status"`
		StartedAt  string  `json:"started_at"`
		FinishedAt *string `json:"finished_at"`
		Error      string  `json:"error"`
	}

	var responseData []ExecutionResponse
	for _, exec := range executions {
		response := ExecutionResponse{
			ID:        exec.ID,
			FlowName:  exec.Flow.Name,
			Status:    exec.Status,
			StartedAt: exec.StartTime.Format("2006-01-02 15:04:05"),
			Error:     exec.Error,
		}
		if exec.EndTime != nil {
			finishedAt := exec.EndTime.Format("2006-01-02 15:04:05")
			response.FinishedAt = &finishedAt
		}
		responseData = append(responseData, response)
	}

	c.JSON(http.StatusOK, NewSuccessResponse(responseData))
}

// GetExecutionNodes 获取执行的节点状态
func (h *Handler) GetExecutionNodes(c *gin.Context) {
	executionId := c.Param("id")
	
	// 获取节点执行记录
	nodeExecutions, err := h.db.GetNodeExecutionsByFlowExecutionID(executionId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}
	
	// 转换为前端期望的格式
	type NodeExecutionResponse struct {
		ID       string `json:"id"`
		NodeName string `json:"node_name"`
		Status   string `json:"status"`
		Error    string `json:"error"`
		Output   string `json:"output"`
	}
	
	var responseData []NodeExecutionResponse
	for _, nodeExec := range nodeExecutions {
		// 获取节点信息以获取节点名称
		node, err := h.db.GetNode(nodeExec.NodeID)
		if err != nil {
			continue // 跳过无法获取节点信息的记录
		}
		
		response := NodeExecutionResponse{
			ID:       nodeExec.ID,
			NodeName: node.Name,
			Status:   nodeExec.Status,
			Error:    nodeExec.Error,
			Output:   nodeExec.Output,
		}
		responseData = append(responseData, response)
	}
	
	c.JSON(http.StatusOK, NewSuccessResponse(responseData))
}

// CreateNotificationConfig 创建通知配置
func (h *Handler) CreateNotificationConfig(c *gin.Context) {
	var config models.NotificationConfig
	if err := c.ShouldBindJSON(&config); err != nil {
		c.JSON(http.StatusBadRequest, NewErrorResponse(400, err.Error()))
		return
	}

	if err := h.db.CreateNotificationConfig(&config); err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}

	c.JSON(http.StatusCreated, NewCreatedResponse(config))
}

// GetNotificationConfigs 获取通知配置
func (h *Handler) GetNotificationConfigs(c *gin.Context) {
	configs, err := h.db.GetNotificationConfigs()
	if err != nil {
		c.JSON(http.StatusInternalServerError, NewErrorResponse(500, err.Error()))
		return
	}

	c.JSON(http.StatusOK, NewSuccessResponse(configs))
}